import { EffectComposer as EffectComposerImpl } from './lib/pp/from-threejs/postprocessing/EffectComposer'
import { RenderPass } from './lib/pp/from-threejs/postprocessing/RenderPass'
import { HalftonePass } from './lib/pp/HalftonePass'
import { getContext, onFrame, onResize } from '../../canvas'

function creaeteComposer(gl, scene, camera, size, disable) {
  // Initialize composer
  const effectComposer = new EffectComposerImpl(gl)
  // Add render pass
  effectComposer.addPass(new RenderPass(scene, camera))

  // Create & add a halftone pass
  const halftoneParams = {
    shape: 1,
    radius: 2,
    rotateR: Math.PI / 12,
    rotateB: (Math.PI / 12) * 2,
    rotateG: (Math.PI / 12) * 3,
    scatter: 1,
    blending: 1,
    blendingMode: 1,
    greyscale: false,
    disable,
  }
  const halftonePass = new HalftonePass(
    size.width,
    size.height,
    halftoneParams
  )
  effectComposer.addPass(halftonePass)

  return effectComposer
}

export default function postProcess(disable = false) {
  const {renderer, scene, camera, size} = getContext()

  const composer = creaeteComposer(renderer, scene, camera, size, disable)

  composer.setSize(size.width, size.height)
  onResize(()=> {
    composer.setSize(size.width, size.height)
  })
  onFrame((_, delta)=> {
    renderer.autoClear = true;
    composer.render(delta)
  })
}
